import React, { Component } from 'react';
import { Modal, Form, Input, Button, Icon, Radio, Row, Col, Select, message } from 'antd';
import classNames from 'classnames';
// import { stringify } from 'query-string';
import qs from 'qs';
import 'whatwg-fetch';
import styles from './Modal.less';
import Loading from './Loading/Loading';
import messageImg from '../assets/errIcon.png';
import { VName } from '~/utils/validate';
import { url } from '~/config';
import close from '../assets/close.png';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const waitTime = 60;

class ModalDialog extends Component {
  constructor(props) {
    super(props)
    this.state = {
      btnTxt: '获取验证码',
      disabled: false,
      hide: this.props.hide,
      infoText: this.props.shopName,
      visible: this.props.visible,
      btnsetInterval: {},
      errText: false,
      returnErrText: '',
      showReturn: false,
    }
  }
  changePhone = () => {
    const phone = this.props.form.getFieldValue('phone');
    const shopper = this.props.form.getFieldValue('shopper');
    if(phone !== this.props.phone || shopper !== this.props.shopNO) {
      this.setState({
          hide: false,
      })
    } else {
      this.setState({
          hide: this.props.hide,
      })
    }
  }
  changeShopNO = () => {
    const phone = this.props.form.getFieldValue('phone');
    const shopper = this.props.form.getFieldValue('shopper');
    if(phone !== this.props.phone || shopper !== this.props.shopNO) {
      this.setState({
        hide: false,
        infoText: '',
      })
    } else {
      this.setState({
        hide: this.props.hide,
        infoText: this.props.shopName,
      })
    }
  }
  componentWillUnmount = () => {
    clearInterval(this.btnsetInterval);
  }
  getShopName = () => {
    const shopper = this.props.form.getFieldValue('shopper');
    const phone = this.props.form.getFieldValue('phone');
    if(!shopper) {
      // this.setState({
      //   returnErrText: '请输入所属门店',
      // })
      return;
    }
    this.setState({
      returnErrText: '',
      showReturn: false,
    })
    // this.setState({
    //   returnErrText: '',
    // })
    // Loading.show();
    fetch(`/clerkconfig/clerkconfig/findStore?storeNo=${shopper}&type=1`, {
      method: 'post',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      credentialss: 'same-origin',
      body: qs.stringify(shopper),
    })
    .then((response) => {
      response.json()
      .then((datas) => {
        console.log(datas)
        if(datas.status === '0') {
          this.setState({
            infoText: datas.body.storeName,
            errText: false,
          })

        } else if (datas.status === '-3') {
          Modal.error({
            title: '获取门店失败',
            content: datas.errorMsg,
            onOk: () => {
              window.location.href = "http://weixin.4000916916.com/wechatBH/oauth2?state=b4e68e3ec8f511e6a96f00163e0a07e1";
            },
          });
        } else {
          this.setState({
            infoText: datas.errorMsg,
            errText: true,
          })
          // this.props.form.setFieldsValue({shopper: ''})
        }
      }).catch((error) => {
        Modal.error({
          title: '接口访问失败',
          content: response.statusText,
        });
      })
    })
  }
  getValidateCode = () => {
    const phone = this.props.form.getFieldValue('phone');
    if (!phone) {
      return;
    }
    const data = {
      phone,
      authCode: window.sessionStorage.authCode,
    }
    // new Promise((resolve, reject) => {
    //    this.props.vaildCode.call(this, data, resolve, reject);
    // })
    // .then((data) => {
    //   // console.log(1);
    //   // console.log(data)
    //   if(datas.status === '0') {
    //     let timeLeft = waitTime;
    //     this.setState({
    //       disabled: true,
    //       returnErrText: '',
    //     })
    //     const self=this;
    //     self.btnsetInterval=setInterval(()=>{
    //       this.setState({
    //         btnTxt: `${timeLeft}s后发送`
    //       })
    //       timeLeft = timeLeft - 1;
    //       if ( timeLeft === 0) {
    //         clearInterval(self.btnsetInterval);
    //         this.setState({
    //           btnTxt: '获取验证码',
    //           disabled: false,
    //         })
    //       }
    //     },1000);
    //   } else {
    //     this.setState({
    //       returnErrText: datas.errorMsg,
    //     })
    //   }
    // })
    // .catch((error) => {
    //   console.log(error);
    //   Modal.error({
    //     title: '接口访问失败',
    //     content: error.err.message,
    //   });
    // })
    this.setState({
                  btnTxt: '获取验证码',
                  disabled: true,
                })
    fetch(`/clerkconfig/clerkconfig/sendSMS.do?phone=${phone}&authCode=${window.sessionStorage.authCode}`, {
        method: 'post',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        credentialss: 'same-origin',
        body: qs.stringify(phone),
      })
    .then((response) => {
        response.json()
        .then((datas) => {
          if(datas.status === '0') {
            let timeLeft = waitTime;
            this.setState({
              disabled: true,
              returnErrText: '',
              showReturn: false,
            })
            const self=this;
            self.btnsetInterval=setInterval(()=>{
              this.setState({
                btnTxt: `${timeLeft}s后发送`
              })
              timeLeft = timeLeft - 1;
              if ( timeLeft === 0) {
                clearInterval(self.btnsetInterval);
                this.setState({
                  btnTxt: '获取验证码',
                  disabled: false,
                })
              }
            },1000);
          } else {
            this.setState({
              returnErrText: datas.errorMsg,
              showReturn: true,
              btnTxt: '获取验证码',
              disabled: false,
            })
          }
        })
        .catch((error) => {
          Modal.error({
            title: '接口访问失败',
            content: response.statusText,
          });
        })
      })
  }
  handleSubmit = (e) => {
   e.preventDefault();
   this.props.form.validateFields((err, values) => {
     values.shopName = this.state.infoText;
     if (!err) {
       new Promise((resolve, reject) =>{
         this.props.update.call(this, values, resolve, reject);
       }).then((data) =>{
        return  new Promise((resolve, reject) =>{
           this.props.query.call(this, { authCode: window.sessionStorage.authCode }, resolve, reject);
         })
       }
     ).catch((error) =>{
       if(error.err.status === '-3') {
         Modal.error({
            title: '提交失败',
            content: error.err.errorMsg,
            onOk: () => {
              window.location.href = url;//重新获取一个code
            },
         });
       } else {
         if(error.err.status === '-4'){
           this.setState({
             infoText: '',
           })
         }
         this.setState({
           returnErrText: error.err.errorMsg,
           showReturn: true,
         })
       }
     })
     }
   });
  }
  validateName = (rule, value, callback) => {
    if(!VName(value)) {
      callback('请输入正确的姓名');
    }
    callback();
  }
  close = (e) => {
    // this.setState({
    //   visible: false,
    // })
    this.props.closeModal();
  }
  render(){
    const { name, phone, shopNO, canClose } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    return (
      <Modal visible={this.state.visible}
        onCancel={this.close}
        footer={null} maskClosable={false}
        closable={false}
        style={{top: 0, zIndex: 10001}}
        className = {styles.Modal}
      >
        <div className={styles.header}>
          <p className={styles.name}>{name}</p>
          <p className={styles.tips}>还差一步，专属页面就属于你的咯</p>
        </div>
        <img src={close} className={classNames({[styles.close]: true, [styles.hideClose]: !canClose})} onClick={this.close} />
        <Form className={styles.form} onSubmit={this.handleSubmit}>
          <FormItem
            {...formItemLayout}
            label="姓名"
            // hasFeedback
          >
            {getFieldDecorator('name', {
              initialValue: name,
              rules: [{
              }, {
                required: true,
                message:'请输入姓名',
              },
              {
                validator: this.validateName,
              }],
            })(
              <Input maxLength="10" placeholder="请输入您的姓名" className={styles.orange}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="手机号码"
            // hasFeedback
          >
            {getFieldDecorator('phone', {
              initialValue:phone,
              rules: [
                {required: true, message: '请输入手机号码'},
             ],
            })(
              <Input placeholder="请输入手机号" className={styles.orange} onKeyUp={this.changePhone}
                maxLength="11"
                type="tel"
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="验证码"
            className={classNames({[styles.hide]: this.state.hide})}
          >
          <Row gutter={8}>
           <Col span={13}>
           {getFieldDecorator('validateCode', {
             rules: [{
               required: !this.state.hide, message: '请输入验证码',
             }],
           })(
             <Input placeholder="请输入验证码" className={styles.orange} type="tel"
            />
           )}
           </Col>
           <Col span={11}>
             <Button className={styles.validateCodeBtn} disabled={this.state.disabled} onClick={this.getValidateCode}>{this.state.btnTxt}</Button>
           </Col>
         </Row>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="所属门店"
            // hasFeedback
          >
          <Row gutter={8}>
            <Col span={13}>
            {getFieldDecorator('shopper', {
              initialValue:shopNO,
              rules: [{
                required: true, message: '请输入所属门店',
              }],
            })(
              <Input placeholder="请输入门店编号" className={styles.orange} onKeyUp={this.changeShopNO}/>
            )}
          </Col>
          <Col span={8}>
            <Button className={styles.searchBtn} onClick={this.getShopName}>查询</Button>
          </Col>
          </Row>
          <p className={classNames({[styles.infoText]: true, [styles.errText]: this.state.errText})}>{this.state.infoText}</p>
          <p className={styles.returnErrText}>{this.state.returnErrText}</p>
          <p className={classNames({[styles.returnErrText]: true, [styles.showReturn]: this.state.showReturn})}>
            <img src={messageImg} className={styles.messageImg} />
            <span className={styles.messageText}>
              {this.state.returnErrText}
            </span>
          </p>
          </FormItem>
          <FormItem className={styles.formbottom}>
            <Button className={styles.submit} htmlType="submit">确定</Button>
          </FormItem>
          <FormItem>
            <p className={styles.metion}>*可联系城市经理或致电4000916916获取门店编号</p>
          </FormItem>
        </Form>
      </Modal>
    )
  }
}

ModalDialog.propTypes = {

}
ModalDialog = Form.create()(ModalDialog)
export default ModalDialog;
